package com.zly.books.controller;

import com.github.pagehelper.PageInfo;
import com.zly.books.entity.Book;
import com.zly.books.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.MultipartFilter;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    BookService bookService;


    @GetMapping
    public String getAllList(Model model){
        List<Book> list = bookService.getAll();
        model.addAttribute("books",list);
        return "/index";
    }

    @GetMapping("/page")
    public String getPage(@RequestParam(defaultValue = "1") Integer pageNum,Model model){
        PageInfo<Book> page = bookService.getPage(pageNum);
        model.addAttribute("page",page);
        return "/index";
    }

    @GetMapping("/del")
    public String del(Integer id,Integer pageNum){
        bookService.del(id);
        return "redirect:/book/page?pageNum="+pageNum;
    }

    @PostMapping("/dels")
    public String dels(Integer[] ids){
         if (ids.length>0){
             bookService.dels(ids);
         }
         return "redirect:/book/page";
    }
    @GetMapping("/sel")
    public String sel(Integer id,Model model){
        Book book = bookService.sel(id);
        model.addAttribute("book",book);
        return "/add";
    }
    @PostMapping("/saveAndUp")
    public String sel(Book book){
        int num = bookService.saveAndUp(book);
        if (num>0){
            return "redirect:/book/page";
        }else {
            return "/add";
        }
    }
    @GetMapping("/add")
    public String add(){
        return "add";
    }
}
